<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="时间维度" style="width: 300px;">
                    <el-select v-model="searchForm.timeDimension" placeholder="请选择时间维度">
                        <el-option label="天" :value="1" />
                        <el-option label="月" :value="2" />
                        <el-option label="年" :value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="时间范围">
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 1" type="date"
                        placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 300px;" />
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 2" type="month"
                        placeholder="选择月份" value-format="YYYY-MM" style="width: 300px;" />
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 3" type="year"
                        placeholder="选择年份" value-format="YYYY" style="width: 300px;" />
                </el-form-item>

                <el-form-item label="区域" style="width: 300px;">
                    <el-select v-model="searchForm.region" placeholder="请选择区域">
                        <el-option v-for="value in regionList" :key="value.id" :label="value.name" :value="value.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站点" style="width: 300px;">
                    <el-select v-model="searchForm.siteIds" multiple placeholder="请选择站点" collapse-tags
                        collapse-tags-tooltip>
                        <el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="监测量" style="width: 300px;">
                    <el-select v-model="searchForm.monitorIds" multiple placeholder="请选择监测量" collapse-tags
                        collapse-tags-tooltip>
                        <el-option v-for="item in monitorList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button @click="targetGroupManagementVisible" icon="Menu">分组管理</el-button>
                    <el-button @click="handleExport" icon="Download">导出数据</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 图表区域 -->
        <el-card class="chart-card mt-2">
            <Echarts :option="chartOption" :style="{ height: '400px' }" ref="chartRef" />
        </el-card>

        <!-- 统计数据区域 -->
        <div class="site-statistics">站点统计数据</div>
        <el-row :gutter="18" class="mt-2">
            <el-col v-for="site in siteStatistics" :span="8" :key="site.siteId" class="mb-2">
                <el-card class="site-stat-card">
                    <div class="title">
                        <div class="icon"></div>
                        <div class="site-name">{{ getName(siteList, site.siteId, 'id', 'name') }}</div>
                    </div>
                    <div class="stat-content">
                        <div class="stat-item">
                            <span class="label">最大压力:</span>
                            <span class="value">{{ (site.maxVal).toFixed(2) }} MPa</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">最小压力:</span>
                            <span class="value">{{ site.minVal.toFixed(2) }} MPa</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">压力振幅:</span>
                            <span class="value">{{ site.amplitude.toFixed(2) }} MPa</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 分组管理对话框 -->
        <el-dialog v-model="groupManagementVisible" title="监测量分组管理" width="60%" :close-on-click-modal="false">
            <el-container>
                <!-- 左侧分组列表 -->
                <el-card>
                    <el-input v-model="groupSearch" placeholder="搜索分组" clearable style="width: 100%" />
                    <el-button type="primary" @click="handleAddGroup" icon="Plus" class="mt-2">
                        新增分组
                    </el-button>
                    <el-scrollbar class="group-list mt-2">
                        <el-menu :default-active="activeGroup" @select="handleGroupSelect">
                            <el-menu-item v-for="group in filteredGroups" :key="group.id" :index="group.id.toString()">
                                <template #title>
                                    <div class="group-item">
                                        <span>{{ group.groupName }}</span>
                                    </div>
                                </template>
                            </el-menu-item>
                        </el-menu>
                    </el-scrollbar>
                </el-card>

                <!-- 右侧分组详情 -->
                <el-main class="group-main">
                    <div v-if="currentGroup">
                        <!-- 分组基本信息 -->
                        <el-card class="group-info-card">
                            <template #header>
                                <div class="group-info-header">
                                    <span>分组信息</span>
                                    <div>
                                        <el-button type="primary" size="small" @click="handleEditGroup">
                                            编辑
                                        </el-button>
                                        <el-button type="danger" size="small" @click="handleDeleteGroup">
                                            删除
                                        </el-button>
                                    </div>
                                </div>
                            </template>
                            <el-descriptions :column="2" border>
                                <el-descriptions-item label="分组名称">{{ currentGroup.groupName }}</el-descriptions-item>
                                <el-descriptions-item label="创建时间">{{ currentGroup.createdAt }}</el-descriptions-item>
                                <el-descriptions-item label="更新时间">{{ currentGroup.updatedAt }}</el-descriptions-item>
                            </el-descriptions>
                        </el-card>

                        <!-- 分组监测量管理 -->
                        <el-card class="group-items-card mt-2">
                            <template #header>
                                <div class="group-items-header">
                                    <span>监测量列表</span>
                                    <div>
                                        <el-button type="primary" size="small" @click="handleSearchGroup">查询</el-button>
                                        <el-button type="primary" size="small" @click="showAddItemDialog">
                                            添加监测量
                                        </el-button>
                                    </div>
                                </div>
                            </template>

                            <el-table :data="groupItems" border v-loading="loading">
                                <el-table-column prop="monitorName" label="监测量名称" align="center" />
                                <el-table-column prop="siteId" label="所属站点" align="center">
                                    <template #default="{ row }">
                                        {{ row.siteId }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="120" align="center">
                                    <template #default="{ row }">
                                        <el-button type="danger" size="small" @click="handleRemoveItem(row)">
                                            移除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-card>
                    </div>

                    <div v-else class="empty-tip">
                        <el-empty description="请从左侧选择一个分组或创建新分组" />
                    </div>
                </el-main>
            </el-container>

            <!-- 新增/编辑分组对话框 -->
            <el-dialog v-model="groupDialog.visible" :title="groupDialog.title" width="500px"
                :close-on-click-modal="false">
                <el-form ref="groupFormRef" :model="groupForm" :rules="groupRules" label-width="100px">
                    <el-form-item label="分组名称" prop="groupName">
                        <el-input v-model="groupForm.groupName" placeholder="请输入分组名称" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="groupDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="submitGroupForm">保存</el-button>
                </template>
            </el-dialog>

            <!-- 添加监测量对话框 -->
            <el-dialog v-model="itemDialog.visible" title="添加监测量到分组" width="600px" :close-on-click-modal="false">
                <el-transfer v-model="selectedItems" :data="availableItems" :titles="['可选监测量', '已选监测量']" :props="{
                    key: 'monitorId',
                    label: 'monitorName'
                }" filterable filter-placeholder="请输入监测量名称" />
                <template #footer>
                    <el-button @click="itemDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddItems">确认添加</el-button>
                </template>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Echarts from '@/components/ECharts'

// 原有API导入
import {
    getSiteList,
    getMonitorList,
    getPressureTrend,
    getSiteStatistics,
    getRegionList,
    listMonitorGroups,
    getMonitorGroupDetail,
    addMonitorGroup,
    updateMonitorGroup,
    deleteMonitorGroups,
    listGroupItems,
    listMonitorItems,
    addItemsToGroup,
    deleteItemFromGroup
} from '@/api/dispatch/analyze/multi_site_curve_analysis'

const { proxy } = getCurrentInstance();
const groupFormRef = ref(null)
// 搜索表单数据
const searchForm = reactive({
    timeDimension: 1,
    time: '',
    region: '',
    monitorIds: [],
    siteIds: []
})

// 数据列表
const siteList = ref([])
const monitorList = ref([])
const pressureData = ref([])
const siteStatistics = ref([])
const regionList = ref([])

// 当前选中的快捷时间
const activeQuickTime = ref('')
const activeTimeRange = ref('30day')

// 加载状态
const loading = ref(false)

// 时间范围按钮
const timeRangeButtons = [
    { label: '24小时', value: '24h' },
    { label: '7天', value: '7day' },
    { label: '30天', value: '30day' },
    { label: '自定义', value: 'custom' }
]

// 图表配置
const chartOption = computed(() => {
    return {
        title: {
            text: '多站点压力变化曲线对比',
            left: 'center',
            textStyle: {
                fontSize: 16,
                fontWeight: 'bold'
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let result = `${params[0].axisValue}<br/>`
                params.forEach(param => {
                    result += `${param.marker} ${param.seriesName}: ${param.value} MPa<br/>`
                })
                return result
            }
        },
        legend: {
            data: pressureData.value?.map(item => item.label || item.metric),
            top: 30,
            right: 50
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: getXAxisData()
        },
        yAxis: {
            type: 'value',
            name: '压力 (MPa)',
            nameTextStyle: {
                padding: [0, 30, 0, 0]
            },
        },
        series: getChartSeries()
    }
})

// 分组管理相关状态
const groupManagementVisible = ref(false)
const groupSearch = ref('')
const activeGroup = ref('')
const currentGroup = ref(null)
const groupItems = ref([])
const groupList = ref([])

// 分组对话框控制
const groupDialog = reactive({
    visible: false,
    title: '新增分组',
    isEdit: false
})

// 分组表单数据
const groupForm = reactive({
    id: undefined,
    groupName: '',
    isPublic: 0,
    remark: ''
})

// 分组表单验证规则
const groupRules = reactive({
    groupName: [
        { required: true, message: '请输入分组名称', trigger: 'blur' }
    ],
    isPublic: [
        { required: true, message: '请选择分组类型', trigger: 'change' }
    ]
})

// 监测量对话框控制
const itemDialog = reactive({
    visible: false
})

// 可用监测量列表
const availableItems = ref([])
const selectedItems = ref([])




// 过滤后的分组列表
const filteredGroups = computed(() => {
    if (!groupSearch.value) return groupList.value
    return groupList.value.filter(group =>
        group.groupName.toLowerCase().includes(groupSearch.value.toLowerCase())
    )
})

const handleSearchGroup = () => {
    searchForm.monitorIds = groupItems.value.map(item => item.monitorId);
    searchForm.siteIds = groupItems.value.map(item => item.siteId);
    console.log(searchForm);
    
    groupManagementVisible.value = false;
    handleSearch();
}

// 获取X轴数据
function getXAxisData() {
    if (!pressureData.value.length) return []
    return pressureData.value[0].points.map(point => point.date.split(' ')[1])
}

const targetGroupManagementVisible = () => {
    // 获取分组信息 
    groupManagementVisible.value = true;
    fetchGroupList();
}

// 获取图表系列数据
function getChartSeries() {
    return pressureData.value.map((item, index) => {
        const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
        return {
            name: item.label || item.metric,
            type: 'line',
            data: item.points.map(point => point.value),
            smooth: true,
            lineStyle: {
                width: 2
            },
            itemStyle: {
                color: colors[index % colors.length]
            },
            symbol: 'circle',
            symbolSize: 6
        }
    })
}

// 获取波动类型
function getAmplitudeType(amplitude) {
    if (amplitude < 0.1) return 'success'
    if (amplitude < 0.2) return 'warning'
    return 'danger'
}

// 查询处理
async function handleSearch() {
    try {
        loading.value = true
        let options = {
            ...searchForm,
            siteIds: searchForm.siteIds.join(),
            monitorIds: searchForm.monitorIds.join()
        }
        const trendRes = await getPressureTrend(options)
        pressureData.value = trendRes.data || []

        const statRes = await getSiteStatistics(options)
        siteStatistics.value = statRes.data || []

        ElMessage.success('数据加载成功')
    } catch (error) {
        ElMessage.error('数据加载失败')
    } finally {
        loading.value = false
    }
}

// 重置搜索
function resetSearch() {
    searchForm.timeDimension = 1
    searchForm.time = new Date().toISOString().split('T')[0]
    searchForm.region = ''
    searchForm.monitorIds = []
    activeQuickTime.value = ''
    activeTimeRange.value = '30day'
}

// 导出数据
function handleExport() {
    let options = {
        ...searchForm,
        siteIds: searchForm.region.join(),
        monitorIds: searchForm.monitorIds.join()
    }
    proxy.download("/dispatch/dispatch/duozhandianquxian/trend/export", {
        ...options,
    }, `user_${new Date().getTime()}.xlsx`);
}

// 获取分组列表
const fetchGroupList = async () => {
    try {
        loading.value = true
        const res = await listMonitorGroups()
        groupList.value = res.data || []
    } catch (error) {
        console.error('获取分组列表失败:', error)
        ElMessage.error('获取分组列表失败')
    } finally {
        loading.value = false
    }
}

// 选择分组
const handleGroupSelect = async (groupId) => {
    activeGroup.value = groupId

    try {
        loading.value = true
        // 获取分组详情
        const detailRes = await getMonitorGroupDetail(groupId)
        currentGroup.value = detailRes.data

        // 获取分组监测量列表
        const itemsRes = await listGroupItems(groupId)
        groupItems.value = itemsRes.data || []
    } catch (error) {
        console.error('获取分组详情失败:', error)
        ElMessage.error('获取分组详情失败')
    } finally {
        loading.value = false
    }
}

// 新增分组
const handleAddGroup = () => {
    groupDialog.visible = true
    groupDialog.title = '新增分组'
    groupDialog.isEdit = false
    resetGroupForm()
}

// 编辑分组
const handleEditGroup = () => {
    groupDialog.visible = true
    groupDialog.title = '编辑分组'
    groupDialog.isEdit = true
    Object.assign(groupForm, currentGroup.value)
}

// 删除分组
const handleDeleteGroup = async () => {
    try {
        await ElMessageBox.confirm(`确认删除分组 "${currentGroup.value.groupName}" 吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteMonitorGroups([currentGroup.value.id])
        ElMessage.success('删除成功')
        fetchGroupList()
        activeGroup.value = ''
        currentGroup.value = null
        groupItems.value = []
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除分组失败:', error)
            ElMessage.error('删除分组失败')
        }
    }
}

// 重置分组表单
const resetGroupForm = () => {
    groupForm.id = undefined
    groupForm.groupName = ''
    groupForm.isPublic = 0
    groupForm.remark = ''
}

// 提交分组表单
const submitGroupForm = async () => {
    try {
        await groupFormRef.value.validate()

        if (groupDialog.isEdit) {
            await updateMonitorGroup(groupForm)
            ElMessage.success('更新成功')
        } else {
            await addMonitorGroup(groupForm)
            ElMessage.success('新增成功')
        }

        groupDialog.visible = false
        fetchGroupList()
    } catch (error) {
        console.error('保存失败:', error)
        if (error !== 'validate') {
            ElMessage.error('操作失败')
        }
    }
}

// 显示添加监测量对话框
const showAddItemDialog = async () => {
    try {
        loading.value = true
        const res = await listMonitorItems(activeGroup.value)
        availableItems.value = res.data || []
        selectedItems.value = []
        itemDialog.visible = true
    } catch (error) {
        console.error('获取监测量列表失败:', error)
        ElMessage.error('获取监测量列表失败')
    } finally {
        loading.value = false
    }
}

// 提交添加监测量
const submitAddItems = async () => {
    if (selectedItems.value.length === 0) {
        ElMessage.warning('请至少选择一个监测量')
        return
    }

    try {
        await addItemsToGroup({
            groupId: currentGroup.value.id,
            itemIds: selectedItems.value
        })
        ElMessage.success('添加成功')
        itemDialog.visible = false
        // 刷新分组监测量列表
        const res = await listGroupItems(currentGroup.value.id)
        groupItems.value = res.data || []
    } catch (error) {
        console.error('添加监测量失败:', error)
        ElMessage.error('添加监测量失败')
    }
}

// 移除监测量
const handleRemoveItem = async (item) => {
    try {
        await ElMessageBox.confirm(`确认从分组中移除监测量 "${item.monitorName}" 吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await deleteItemFromGroup(item.id)
        ElMessage.success('移除成功')
        // 刷新分组监测量列表
        const res = await listGroupItems(currentGroup.value.id)
        groupItems.value = res.data || []
    } catch (error) {
        if (error !== 'cancel') {
            console.error('移除监测量失败:', error)
            ElMessage.error('移除监测量失败')
        }
    }
}

// 初始化数据
async function initData() {
    // 获取站点列表
    const siteRes = await getSiteList()
    siteList.value = siteRes.data || []
    searchForm.siteIds = [siteList.value[0].id];

    // 获取监测点列表
    const monitorRes = await getMonitorList();
    monitorList.value = monitorRes.data || [];
    searchForm.monitorIds = [monitorList.value[0].id];
    // 设置默认时间
    searchForm.time = new Date().toISOString().split('T')[0]

    const { data } = await getRegionList(searchForm);
    regionList.value = data;
    searchForm.region = regionList.value[0].id;

    handleSearch();
}

onMounted(() => {
    initData();
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.quick-time-select {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
}

.quick-time-select .el-button {
    margin-right: 10px;
    margin-bottom: 5px;
}

.chart-card,
.stats-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-tools {
    display: flex;
    align-items: center;
    gap: 10px;
}

.site-stat-card {
    height: 100%;
}

.site-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.site-name {
    font-weight: bold;
    font-size: 14px;
}

.stat-content {
    padding: 5px 0;
}

.stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 13px;
}

.stat-item .label {
    color: #666;
}

.stat-item .value {
    font-weight: bold;
    color: #333;
}

.mt-2 {
    margin-top: 20px;
}

.mb-2 {
    margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-form .el-form-item {
        width: 100% !important;
        margin-right: 0;
    }

    .card-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }

    .header-tools {
        width: 100%;
        justify-content: space-between;
    }
}

.site-statistics {
    font-size: 20px;
    font-weight: bold;
}

.title {
    display: flex;
    align-items: center;
}

.site-name {
    font-size: 18px;
    position: relative;
    margin-left: 10px;
}

.icon {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: forestgreen;
}

.stat-content {
    display: flex;
    margin: 20px 10px;
    justify-content: space-around;
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: space-between;
}

.stat-item .label {
    font-size: 16px;
}

.stat-item .value {
    margin-top: 10px;
    font-size: 18px;
}

/* 分组管理相关样式 */
.group-aside {
    border-right: 1px solid #e6e6e6;
    padding-right: 20px;
}

.group-header {
    padding: 10px;
    border-bottom: 1px solid #e6e6e6;
}

.group-list {
    height: 50vh;
}

.group-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.group-main {
    padding: 0 20px;
}

.group-info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.group-items-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.empty-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}
</style>